package com.question.service.impl;

import com.question.context.BaseContext;
import com.question.exception.BaseException;
import com.question.mapper.MajorMapper;
import com.question.pojo.entity.Major;
import com.question.service.MajorService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class MajorServiceImpl implements MajorService {

    @Autowired
    private MajorMapper majorMapper;

    @Autowired
    private CategoryServiceImpl categoryService;

    /**
     * 获取所有专业
     * @return
     */
    @Override
    public List<Major> getAllMajors() {
        return majorMapper.selectAllMajors();
    }

    @Override
    public Major getMajorById(Integer majorId) {
        return majorMapper.getMajorById(majorId);
    }

    @Override
    @Transactional
    public void addMajor(Major major) {
        majorMapper.insertMajor(major);
    }

    @Override
    @Transactional
    public void updateMajor(Major major) {
        majorMapper.updateMajor(major);
    }

    @Override
    @Transactional
    public void deleteMajor(Integer majorId) {
        // 检查是否有分类关联该专业
        int categoryCount = categoryService.countCategoriesByMajor(majorId);
        if (categoryCount > 0) {
            throw new BaseException("该专业下存在分类，无法删除");
        }

        majorMapper.deleteMajor(majorId);
    }

    /**
     * 获取当前用户专业信息
     * @return
     */
    public Major getMajorByUserId() {
        Long userId = BaseContext.getCurrentId();
        return majorMapper.getMajorByUserId(userId);
    }
}